import { api } from './api'
import {
  Article,
  CreateArticleRequest,
  UpdateArticleRequest,
  GetArticlesParams,
  PaginatedResponse,
  ApiResponse
} from '../../types/article'

export const articlesApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getArticles: builder.query<ApiResponse<PaginatedResponse<Article>>, GetArticlesParams>({
      query: (params) => ({
        url: '/articles',
        method: 'GET',
        params
      }),
      providesTags: (result) =>
        result
          ? [
              ...result.data.content.map(({ id }) => ({ type: 'Article' as const, id })),
              { type: 'Article' as const, id: 'LIST' }
            ]
          : [{ type: 'Article' as const, id: 'LIST' }]
    }),

    getArticle: builder.query<ApiResponse<Article>, number>({
      query: (id) => `/articles/${id}`,
      providesTags: (_, __, id) => [{ type: 'Article' as const, id }]
    }),

    createArticle: builder.mutation<ApiResponse<Article>, CreateArticleRequest>({
      query: (data) => ({
        url: '/articles',
        method: 'POST',
        body: data
      }),
      invalidatesTags: [{ type: 'Article', id: 'LIST' }]
    }),

    updateArticle: builder.mutation<ApiResponse<Article>, UpdateArticleRequest>({
      query: ({ id, ...data }) => ({
        url: `/articles/${id}`,
        method: 'PUT',
        body: data
      }),
      invalidatesTags: (_, __, { id }) => [
        { type: 'Article', id },
        { type: 'Article', id: 'LIST' }
      ]
    }),

    deleteArticle: builder.mutation<void, number>({
      query: (id) => ({
        url: `/articles/${id}`,
        method: 'DELETE'
      }),
      invalidatesTags: (_, __, id) => [
        { type: 'Article', id },
        { type: 'Article', id: 'LIST' }
      ]
    }),

    likeArticle: builder.mutation<void, number>({
      query: (id) => ({
        url: `/articles/${id}/like`,
        method: 'POST'
      }),
      invalidatesTags: (_, __, id) => [{ type: 'Article', id }]
    }),

    unlikeArticle: builder.mutation<ApiResponse<void>, number>({
      query: (id) => ({
        url: `/articles/${id}/unlike`,
        method: 'POST',
      }),
      invalidatesTags: (_, __, id) => [{ type: 'Article', id }],
    }),

    uploadCover: builder.mutation<ApiResponse<{ cover: string }>, FormData>({
      query: (data) => ({
        url: '/articles/cover',
        method: 'POST',
        body: data,
      }),
    }),
  }),
})

export const {
  useGetArticlesQuery,
  useGetArticleQuery,
  useCreateArticleMutation,
  useUpdateArticleMutation,
  useDeleteArticleMutation,
  useLikeArticleMutation,
  useUnlikeArticleMutation,
  useUploadCoverMutation,
} = articlesApi 